package com.heima.studentinfoplus.service.impl;

import com.heima.studentinfoplus.config.JwtUtil;
import com.heima.studentinfoplus.entity.LoginRequest;
import com.heima.studentinfoplus.entity.LoginResponse;
import com.heima.studentinfoplus.entity.User;
import com.heima.studentinfoplus.repository.UserRepository;
import com.heima.studentinfoplus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    public static final int ROLE_STUDENT = 1;
    public static final int ROLE_ADMIN = 2;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public User register(User user) {
        // Check if the username already exists
        if (userRepository.findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("Username already exists");
        }
        return userRepository.save(user);
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        int roleInt;
        if ("student".equals(request.getRole())) {
            roleInt = ROLE_STUDENT;
        } else if ("admin".equals(request.getRole())) {
            roleInt = ROLE_ADMIN;
        } else {
            return new LoginResponse(-1, "无效的角色", null, null, null);
        }

        User user = userRepository.findByUsernameAndRole(request.getUsername(), roleInt);


        if (user == null) {
            return new LoginResponse(-1, "用户不存在", null, null, null);
        }

        if (!request.getPassword().equals(user.getPassword())) {
            return new LoginResponse(-1, "密码错误", null, null, null);
        }

        String token = jwtUtil.generateToken(Long.toString(user.getId()));
        return new LoginResponse(0, "登录成功", token, request.getRole(), user.getId());
    }

    /**
     * 实现 Spring Security 的 loadUserByUsername 方法
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .roles(getRoleName(user.getRole())) // 假设 role 是 int 类型
                .build();
    }

    // 将角色 int 转换为字符串角色名（如 ROLE_STUDENT）
    private String getRoleName(int role) {
        switch (role) {
            case 0:
                return "STUDENT";
            case 1:
                return "ADMIN";
            default:
                throw new IllegalArgumentException("未知角色: " + role);
        }
    }
}